package parser

import (
	"bufio"
	"strings"

	"gitee.com/tonyjia/gb28181/pkg/model"
	"github.com/ghettovoice/gosip/sip"
	"github.com/sirupsen/logrus"
)

func DeviceFromRequest(req sip.Request) (model.Device, bool) {
	d := model.Device{}

	from, ok := req.From()
	if !ok {
		logrus.Debugln("从请求中无法解析from头部信息", req.String())
		return d, false
	}
	if from.Address == nil {
		logrus.Debugln("从请求中无法解析from头address部分信息", req.String())
		return d, false
	}
	if from.Address.User() == nil {
		logrus.Debugln("从请求中无法解析from头user部分信息", req.String())
		return d, false
	}

	d.DeviceID = from.Address.User().String()
	d.Region = from.Address.Host()
	via, ok := req.ViaHop()
	if !ok {
		logrus.Debugln("从请求中无法解析出via头部信息", via.String())
		return d, false
	}
	d.Host = via.Host
	d.Port = via.Port.String()
	d.TransPort = via.Transport
	logrus.Debugf("从请求中解析出的设备信息: %v\n", d)
	return d, true
}

// SDP信息结构体
type SDPInfo struct {
	Owner       string
	SessionName string
	Connection  string
	Media       string
}

// 解析SDP信息
func ParseSDP(sdpData string) (*SDPInfo, error) {
	sdpInfo := &SDPInfo{}
	scanner := bufio.NewScanner(strings.NewReader(sdpData))
	for scanner.Scan() {
		line := scanner.Text()
		switch {
		case strings.HasPrefix(line, "o="):
			sdpInfo.Owner = line[2:]
		case strings.HasPrefix(line, "s="):
			sdpInfo.SessionName = line[2:]
		case strings.HasPrefix(line, "c="):
			sdpInfo.Connection = line[2:]
		case strings.HasPrefix(line, "m="):
			sdpInfo.Media = line[2:]
		}
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return sdpInfo, nil
}
